// 全局变量
let editingBudgetId = null;
let deletingBudgetId = null;

// 初始化页面
function initPage() {
    // 初始化预算管理器
    const budgetManager = new window.AppData.BudgetManager();
    
    // 渲染分类选择器
    renderCategorySelect();
    
    // 刷新预算列表
    refreshBudgetList();
    
    // 更新预算概览
    updateBudgetSummary();
}

// 渲染分类选择器
function renderCategorySelect() {
    const categorySelect = document.getElementById('categorySelect');
    const expenseCategories = window.AppData.expenseCategories;
    
    let html = '<option value="">请选择分类</option>';
    
    expenseCategories.forEach(category => {
        html += `<option value="${category.id}">${category.name}</option>`;
    });
    
    categorySelect.innerHTML = html;
}

// 刷新预算列表
function refreshBudgetList() {
    const budgetManager = new window.AppData.BudgetManager();
    const budgetUsage = budgetManager.getCurrentBudgetUsage();
    
    const budgetListElement = document.getElementById('budgetList');
    const emptyStateElement = document.getElementById('emptyState');
    
    // 没有预算时显示空状态
    if (budgetUsage.length === 0) {
        budgetListElement.style.display = 'none';
        emptyStateElement.style.display = 'block';
        return;
    }
    
    // 有预算时隐藏空状态
    budgetListElement.style.display = 'block';
    emptyStateElement.style.display = 'none';
    
    // 构建HTML
    let html = '';
    
    budgetUsage.forEach(budget => {
        // 获取分类信息
        const category = getCategoryById(budget.categoryId);
        
        // 确定进度条颜色
        let progressClass = 'progress-normal';
        if (budget.percentage >= 80 && budget.percentage < 100) {
            progressClass = 'progress-warning';
        } else if (budget.percentage >= 100) {
            progressClass = 'progress-danger';
        }
        
        html += `
            <div class="budget-item">
                <div class="budget-header">
                    <div class="budget-category">
                        <div class="category-icon">
                            <i class="material-icons">${category ? category.icon : 'help'}</i>
                        </div>
                        <div class="category-name">${category ? category.name : '未知分类'}</div>
                    </div>
                    <div class="budget-actions">
                        <div class="budget-edit" onclick="editBudget('${budget.id}')">
                            <i class="material-icons">edit</i>
                        </div>
                        <div class="budget-delete" onclick="deleteBudget('${budget.id}')">
                            <i class="material-icons">delete</i>
                        </div>
                    </div>
                </div>
                <div class="budget-details">
                    <div class="budget-amount">
                        <div class="amount-label">预算</div>
                        <div class="amount-value">¥${budget.amount.toFixed(2)}</div>
                    </div>
                    <div class="budget-amount">
                        <div class="amount-label">已使用</div>
                        <div class="amount-value">¥${budget.spent.toFixed(2)}</div>
                    </div>
                    <div class="budget-amount">
                        <div class="amount-label">剩余</div>
                        <div class="amount-value">¥${budget.remaining.toFixed(2)}</div>
                    </div>
                    <div class="budget-progress">
                        <div class="progress-bar ${progressClass}" style="width: ${budget.percentage}%"></div>
                    </div>
                </div>
            </div>
        `;
    });
    
    budgetListElement.innerHTML = html;
}

// 更新预算概览
function updateBudgetSummary() {
    const budgetManager = new window.AppData.BudgetManager();
    const budgetUsage = budgetManager.getCurrentBudgetUsage();
    
    let totalBudget = 0;
    let totalSpent = 0;
    let totalRemaining = 0;
    
    budgetUsage.forEach(budget => {
        totalBudget += budget.amount;
        totalSpent += budget.spent;
    });
    
    totalRemaining = totalBudget - totalSpent;
    
    // 更新UI
    document.querySelector('#totalBudget .summary-value').textContent = `¥${totalBudget.toFixed(2)}`;
    document.querySelector('#totalSpent .summary-value').textContent = `¥${totalSpent.toFixed(2)}`;
    document.querySelector('#totalRemaining .summary-value').textContent = `¥${totalRemaining.toFixed(2)}`;
}

// 获取分类信息
function getCategoryById(categoryId) {
    return window.AppData.expenseCategories.find(category => category.id === categoryId);
}

// 打开添加预算模态框
function openAddBudgetModal() {
    document.getElementById('modalTitle').textContent = '添加预算';
    document.getElementById('categorySelect').value = '';
    document.getElementById('budgetAmountInput').value = '';
    editingBudgetId = null;
    
    // 显示模态框
    document.getElementById('budgetModal').style.display = 'flex';
}

// 打开编辑预算模态框
function editBudget(budgetId) {
    const budgetManager = new window.AppData.BudgetManager();
    const budgets = budgetManager.getBudgets();
    
    const budget = budgets.find(b => b.id === budgetId);
    if (!budget) return;
    
    document.getElementById('modalTitle').textContent = '编辑预算';
    document.getElementById('categorySelect').value = budget.categoryId;
    document.getElementById('budgetAmountInput').value = budget.amount;
    editingBudgetId = budgetId;
    
    // 显示模态框
    document.getElementById('budgetModal').style.display = 'flex';
}

// 关闭模态框
function closeModal() {
    document.getElementById('budgetModal').style.display = 'none';
}

// 保存预算
function saveBudget() {
    const categoryId = document.getElementById('categorySelect').value.trim();
    const amountInput = document.getElementById('budgetAmountInput').value.trim();
    
    // 验证
    if (!categoryId) {
        showToast('请选择分类', true);
        return;
    }
    
    if (!amountInput || isNaN(amountInput) || parseFloat(amountInput) <= 0) {
        showToast('请输入有效金额', true);
        return;
    }
    
    const amount = parseFloat(amountInput);
    
    // 初始化预算管理器
    const budgetManager = new window.AppData.BudgetManager();
    
    if (editingBudgetId) {
        // 编辑现有预算
        const budgets = budgetManager.getBudgets();
        const index = budgets.findIndex(b => b.id === editingBudgetId);
        
        if (index !== -1) {
            const updatedBudget = {
                ...budgets[index],
                categoryId: categoryId,
                amount: amount
            };
            
            budgetManager.updateBudget(updatedBudget);
        }
    } else {
        // 添加新预算
        const newBudget = {
            categoryId: categoryId,
            amount: amount
        };
        
        // 检查是否已存在该分类的预算
        const existingBudgets = budgetManager.getBudgets();
        const existingBudget = existingBudgets.find(b => b.categoryId === categoryId);
        
        if (existingBudget) {
            showToast('该分类已有预算，请先删除或编辑现有预算', true);
            return;
        }
        
        budgetManager.addBudget(newBudget);
    }
    
    // 关闭模态框
    closeModal();
    
    // 刷新预算列表
    refreshBudgetList();
    
    // 更新预算概览
    updateBudgetSummary();
    
    // 显示成功提示
    showToast(editingBudgetId ? '预算已更新' : '预算已添加');
}

// 删除预算
function deleteBudget(budgetId) {
    deletingBudgetId = budgetId;
    document.getElementById('deleteModal').style.display = 'flex';
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    deletingBudgetId = null;
}

// 确认删除预算
function confirmDeleteBudget() {
    if (!deletingBudgetId) return;
    
    // 初始化预算管理器
    const budgetManager = new window.AppData.BudgetManager();
    
    // 删除预算
    const success = budgetManager.deleteBudget(deletingBudgetId);
    
    if (success) {
        // 关闭模态框
        closeDeleteModal();
        
        // 刷新预算列表
        refreshBudgetList();
        
        // 更新预算概览
        updateBudgetSummary();
        
        // 显示成功提示
        showToast('预算已删除');
    } else {
        showToast('删除预算失败', true);
    }
}

// 显示提示
function showToast(message, isError = false) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.classList.add('show');
    
    if (isError) {
        toast.classList.add('error');
    } else {
        toast.classList.remove('error');
    }
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage); 